/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JFrameAgenda.java
 *
 * Created on 29/10/2011, 13:00:03
 */
package visao;

import controle.VeterinarioDAO;
import modelo.Agenda;
import controle.AgendaDAO;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import modelo.Compromisso;
import modelo.Veterinario;

/**
 *
 * @author David
 */
public class JFrameAgenda extends javax.swing.JFrame {

    /** Creates new form JFrameAgenda */
    public JFrameAgenda() {
        initComponents();
        
        /**
         * popula a combo de veterinarios
         */
        VeterinarioDAO _lvet = new VeterinarioDAO();
    
        cmbVeterinario.removeAllItems();

        for (Veterinario _vet : _lvet.getVeterinarios()){
            cmbVeterinario.addItem(_vet.getCRV() + " - " + _vet.getNome());
        }
        
        /**
         * Redefine o tamanho das colunas da agenda
         */
        this.redefinirTamanhoColunas();
    }

    /**
     * redefine o tamanho das colunas
     */
    private void redefinirTamanhoColunas(){
    
        jTableAgenda.getColumnModel().getColumn(0).setResizable(false); //id do compromisso
        jTableAgenda.getColumnModel().getColumn(0).setPreferredWidth(0); //id do compromisso
        jTableAgenda.getColumnModel().getColumn(0).setWidth(0); //id do compromisso
        jTableAgenda.getColumnModel().getColumn(0).setMinWidth(0); //id do compromisso
        jTableAgenda.getColumnModel().getColumn(0).setMaxWidth(0); //id do compromisso
        jTableAgenda.getColumnModel().getColumn(1).setPreferredWidth(60); //horario
        jTableAgenda.getColumnModel().getColumn(2).setPreferredWidth(100);//animalNome
        jTableAgenda.getColumnModel().getColumn(3).setPreferredWidth(370);//Descricao
        jTableAgenda.getColumnModel().getColumn(4).setPreferredWidth(120);//telefone de contato
            
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblAbrirAgenda = new javax.swing.JLabel();
        cmbVeterinario = new javax.swing.JComboBox();
        jCalendarAgenda = new com.toedter.calendar.JCalendar();
        jLabel18 = new javax.swing.JLabel();
        jScrollPaneAgenda = new javax.swing.JScrollPane();
        jTableAgenda = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Agenda");

        lblAbrirAgenda.setFont(new java.awt.Font("Verdana", 0, 12));
        lblAbrirAgenda.setForeground(new java.awt.Color(51, 51, 51));
        lblAbrirAgenda.setText("Abrir Agenda do Veterinario:");

        cmbVeterinario.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N
        cmbVeterinario.setForeground(new java.awt.Color(51, 51, 51));
        cmbVeterinario.setFocusable(false);
        cmbVeterinario.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbVeterinarioItemStateChanged(evt);
            }
        });

        jCalendarAgenda.setForeground(new java.awt.Color(51, 51, 51));
        jCalendarAgenda.setFont(new java.awt.Font("Verdana", 0, 11));

        jLabel18.setFont(new java.awt.Font("Verdana", 0, 18));
        jLabel18.setForeground(new java.awt.Color(102, 102, 255));
        jLabel18.setText("Agenda de Veterinários");
        jLabel18.setName("lblCadastroAnimal"); // NOI18N

        jTableAgenda.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N
        jTableAgenda.setForeground(new java.awt.Color(51, 51, 51));
        jTableAgenda.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, "08:00", null, null, null},
                {null, "08:30", null, null, null},
                {null, "09:00", null, null, null},
                {null, "09:30", null, null, null},
                {null, "10:00", null, null, null},
                {null, "10:30", null, null, null},
                {null, "11:00", null, null, null},
                {null, "11:30", null, null, null},
                {null, "12:00", null, null, null},
                {null, "12:30", null, null, null},
                {null, "13:00", null, null, null},
                {null, "13:30", null, null, null},
                {null, "14:00", null, null, null},
                {null, "14:30", null, null, null},
                {null, "15:00", null, null, null},
                {null, "15:30", null, null, null},
                {null, "16:00", null, null, null},
                {null, "16:30", null, null, null},
                {null, "17:00", null, null, null},
                {null, "17:30", null, null, null},
                {null, "18:00", null, null, null},
                {null, "18:30", null, null, null},
                {null, "19:00", null, null, null},
                {null, "19:30", null, null, null},
                {null, "20:00", null, null, null},
                {null, "20:30", null, null, null},
                {null, "21:00", null, null, null}
            },
            new String [] {
                "ID", "Horário", "Animal", "Atividade", "Telefone"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, true, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableAgenda.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPaneAgenda.setViewportView(jTableAgenda);

        jButton1.setText("Salvar Agenda");
        jButton1.setName("btnSalvarAgenda"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Atualizar Agenda");
        jButton2.setName("btnAtualizarAgenda"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel18)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(lblAbrirAgenda, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmbVeterinario, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(18, 18, 18)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPaneAgenda, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 657, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jCalendarAgenda, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton2))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel18)
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblAbrirAgenda, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbVeterinario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jCalendarAgenda, javax.swing.GroupLayout.PREFERRED_SIZE, 427, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2))
                    .addComponent(jScrollPaneAgenda, javax.swing.GroupLayout.PREFERRED_SIZE, 482, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents


    private void cmbVeterinarioItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cmbVeterinarioItemStateChanged
        
        //regarrega a agenda
        this.recarregarAgenda();

    }//GEN-LAST:event_cmbVeterinarioItemStateChanged

    /**
     * Recarrega os compromissos na agenda com base no Veterinario e na Data
     * @param CRV
     * @param Data 
     */
    private void recarregarAgenda(){

        // Atualiza a agenda conforme é selecionado o veterinario
        String _sCRV = cmbVeterinario.getSelectedItem().toString();
        int CRV  = Integer.parseInt(_sCRV.substring(0, _sCRV.indexOf(" - ")));

        // pega a data da agenda que tgem que mostrar
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String Data = sdf.format(jCalendarAgenda.getCalendar().getTime());
        
        
        AgendaDAO _agendaDAO = new AgendaDAO();
        _agendaDAO.dataDosCompromissos = Data;

        Agenda _agenda = _agendaDAO.getAgenda(CRV);

        // mostra os compromissos
        limparAsLinhasDaAgenda();

        for(Compromisso _c : _agenda.getCompromissos()){
            int _linha = getLinhaDoHorario(_c.getHorario());

            jTableAgenda.setValueAt(_c.getCodigoCompromisso(), _linha, 0);
            jTableAgenda.setValueAt(_c.getHorario(), _linha, 1);
            jTableAgenda.setValueAt(_c.getAnimalNome(), _linha, 2);
            jTableAgenda.setValueAt(_c.getDescricao(), _linha, 3);
            jTableAgenda.setValueAt(_c.getTelefone(), _linha, 4);
        }
    }    
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        // define o veterinario da agenda            
        String _sCRV = cmbVeterinario.getSelectedItem().toString();
        int _iCRV  = Integer.parseInt(_sCRV.substring(0, _sCRV.indexOf(" - ")));
        
        // pega a data da agenda que tgem que gravar
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String data = sdf.format(jCalendarAgenda.getCalendar().getTime());
        
        //pega os dados da tabela para gravar
        
        Agenda _a = new Agenda();
        _a.setCodigoAgenda(new AgendaDAO().getCodigoAgenda(_iCRV));
        
        List<Compromisso> _lc = new ArrayList<Compromisso>();
        
        DefaultTableModel tbm = (DefaultTableModel)jTableAgenda.getModel();
        for(int i = 0; i <= tbm.getRowCount()-1; i++){
            
            String sGrava = jTableAgenda.getValueAt(i, 2).toString() ;
            
            if (sGrava != null && !sGrava.equals(""))
            {
                Compromisso _c = new Compromisso();

                _c.setHorario(jTableAgenda.getValueAt(i, 1).toString());
                _c.setAnimalNome(jTableAgenda.getValueAt(i, 2).toString());
                _c.setDescricao(jTableAgenda.getValueAt(i, 3).toString());
                _c.setTelefone(jTableAgenda.getValueAt(i, 4).toString());
                _c.setDataCompromisso(data);

                _lc.add(_c);            
            }
        }         
        _a.setCompromissos(_lc);        
        _a.setVeterinario(new VeterinarioDAO().getVeterinarioByCRV(_iCRV));
        
        AgendaDAO _aDAO = new AgendaDAO();
        _aDAO.salvarAgenda(_a);
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.recarregarAgenda();        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * Retorna a linha do horario
     * @param horario
     * @return 
     */
    private int getLinhaDoHorario(String horario){
    
        int ret = -1;
        DefaultTableModel tbm = (DefaultTableModel)jTableAgenda.getModel();
        
        for(int i = 0; i <= tbm.getRowCount()-1; i++){
            String _h = (String)jTableAgenda.getValueAt(i, 1);
            if (_h.equals(horario)){
                ret = i;
                break;
            }            
        }        
        return ret;
    }
    
    /**
     * Limpa as linhas da agenda
     */
    private void limparAsLinhasDaAgenda(){
        DefaultTableModel tbm = (DefaultTableModel)jTableAgenda.getModel();
        for(int i = 0; i <= tbm.getRowCount()-1; i++){
            jTableAgenda.setValueAt("", i, 0);
            jTableAgenda.setValueAt("", i, 2);
            jTableAgenda.setValueAt("", i, 3);
            jTableAgenda.setValueAt("", i, 4);
        }       
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrameAgenda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrameAgenda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrameAgenda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameAgenda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JFrameAgenda().setVisible(true);
            }
            
        });
        
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cmbVeterinario;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private com.toedter.calendar.JCalendar jCalendarAgenda;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JScrollPane jScrollPaneAgenda;
    private javax.swing.JTable jTableAgenda;
    private javax.swing.JLabel lblAbrirAgenda;
    // End of variables declaration//GEN-END:variables
}
